const util = require('../../../utils/util.js')
const analysis = require('../../../utils/dataAnalysi.js')

function inArray(arr, key ,val){
    for (let i = 0; i < arr.length; i++) {
        if (arr[i][key] === val) {
            return i
        }
    }
    return -1
}
// ArrayBuffer转16进度字符串示例
function ab2hex(buffer) {
    const hexArr = Array.prototype.map.call(
      new Uint8Array(buffer),
      function (bit) {
        return (`00${bit.toString(16)}`).slice(-2)
      }
    )
    return hexArr.join('')
  }

var appInstance = getApp()
var that = this
Page({

    /**
     * 页面的初始数据
     */
    data: {
        connected_device:'',
        connected:false,
        devices:[],
        _discoveryStarted: false,
        chs: [],
        name: "",
        deviceid:"",
    },

    getConnectedDevice(){
        wx.getConnectedBluetoothDevices({
          services: ['2344C100-7994-1CCA-B98B-00FFD0B3CA8A','0000180A-0000-1000-8000-00805F9B34FB'],
          success(res){
            console.log(res)
        }
        })
    },
    openAdapter(){
        appInstance.openBleAdapter((response) =>{
            console.log('adapter:',response)
        })        
    },
    closeAdapter(){
        appInstance.closeBleAdapter({

        })       
    },
    startScanECG(){
        appInstance.startScan((response) => {
            var msg = response['errMsg']
            if (msg == 'startBluetoothDevicesDiscovery:fail 请先调用 wx.openBluetoothAdapter 接口进行初始化操作'){
                msg = 'not open Adapter'
                wx.showToast({
                    title: msg,
                })
            }
            console.log('获取到回调内容:',response)
            if (msg == 'startBluetoothDevicesDiscovery:ok') {
                this.onBluetoothDeviceFound()
            }
        })
    },
    onBluetoothDeviceFound(){
        console.log('onBluetoothDeviceFound')
        wx.onBluetoothDeviceFound((res) => {
            res.devices.forEach(device => {
                // console.log(device)
                if (!device.name && !device.localName) {
                    return
                }
                if (device.name.indexOf('ECGRec') < 0) {
                    return
                }
                if (device.name.length != 21) {
                    return
                }
                const foundDevices = this.data.devices
                const idx = inArray(foundDevices, 'deviceId', device.deviceId)
                const data = {}
                if (idx === -1) {
                    data[`devices[${foundDevices.length}]`] = device
                } else {
                    // data[`devices[${idx}]`] = device
                    return
                }
                this.setData(data)
            })
          })
    },
    stopScanECG(){
        appInstance.stopScan((response) =>{
            // console.log(response)
        })
    },
    connectECG(e){
        this.stopScanECG()
        const ds = e.currentTarget.dataset
        const deviceId = ds.deviceId
        const name = ds.name
        console.log('连接的设备id ',deviceId)
        console.log('连接的设备名 ', name)
        wx.showLoading({
            title: 'connecting '+name,
        })
        appInstance.connectSensor(deviceId,30*1000,(response) =>{
            console.log(response)
            wx.hideLoading({
                success: (res) => {},
            })
            if (response == '连接成功') {
                this.setData({
                    connected: true,
                    name: name,
                    deviceid:deviceId,
                    devices: [],
                })
                let batteryValue = appInstance.globalData.ecg.battery
                appInstance.globalData.ecg = {connected:true,battery:batteryValue}
                setTimeout(function() {
                    wx.reLaunch({
                      url: '../../dashboard/dashboard',
                    })
                    // wx.navigateBack({
                    //     delta:1
                    // })
                },2000)
            }else {
                wx.showToast({
                  title: response,
                })
            }
        })
        // wx.onBLECharacteristicValueChange((characteristic) => {
        //     const idx = inArray(this.data.chs, 'uuid', characteristic.characteristicId)
        //     const data = {}
        //     // console.log('收到特征uuid:',characteristic.characteristicId)
        //     // console.log('收到的ori数据:',characteristic.value)
        //     console.log('收到的数据:',ab2hex(characteristic.value))
        //     var byteArray = new Uint8Array(characteristic.value)
        //     var valueStr = ab2hex(characteristic.value)
        //     var data_type = ''
        //     if (characteristic.characteristicId == '00002A29-0000-1000-8000-00805F9B34FB') {
        //         //设备信息
        //         data_type = '设备信息'
        //         valueStr = util.utf8ByteToUnicodeStr(byteArray)
        //     }else if (characteristic.characteristicId == '00002A27-0000-1000-8000-00805F9B34FB') {
        //         data_type = '硬件版本号'
        //         valueStr = util.utf8ByteToUnicodeStr(byteArray)
        //     }else if (characteristic.characteristicId == '00002A26-0000-1000-8000-00805F9B34FB') {
        //         data_type = '固件版本号'
        //         valueStr = util.utf8ByteToUnicodeStr(byteArray)
        //     }else if (characteristic.characteristicId == '2344C102-7994-1CCA-B98B-00FFD0B3CA8A') {
        //         let dataDict = analysis.analysisData(byteArray)
        //         data_type = dataDict.type
        //         valueStr = dataDict.value
        //         if (data_type == "Battery") {
        //             // appInstance.globalData.ecg.battery = valueStr
        //             appInstance.globalData.ecg = {battery:valueStr,connected:true}

        //         }
        //     }
        //     if (idx === -1) {
        //       data[`chs[${this.data.chs.length}]`] = {
        //         dataType: data_type,
        //         value: valueStr
        //       }
        //     } else {
        //       data[`chs[${idx}]`] = {
        //         dataType: data_type,
        //         value: valueStr
        //       }
        //     }
        //     // wx.showToast({
        //     //   title: '收到数据',
        //     // })
        //     // data[`chs[${this.data.chs.length}]`] = {
        //     //   uuid: characteristic.characteristicId,
        //     //   value: ab2hex(characteristic.value)
        //     // }
        //     this.setData(data)
        // })
    },
    sendReplyEcgCommand(){
        appInstance.writeBLECharacteristicValue(util.sendNextAckCommand())
    },
    readPatchStatus(){
        appInstance.writeBLECharacteristicValue(util.readPathStatus())
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        let ecgDict = appInstance.globalData.ecg
        if (ecgDict == null) {
            appInstance.globalData.ecg = {
                connected:false,
                battery: "100",
              }
        }
        console.log(appInstance.globalData.ecg.battery)
        //测试全局变量使用
        // var app = getApp()
        // let connect_status = app.globalData.sensor_connected
        // this.setData({
        //     connected:connect_status,
        // })
        //全局函数的调用
        // app.startScan()
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
})